package com.asia5b.a5mall.middleware.base

import android.app.Dialog
import android.content.Context
import android.os.Bundle
import android.view.Gravity
import android.view.View
import android.view.Window
import android.view.WindowManager
import androidx.annotation.FloatRange
import androidx.annotation.StringRes
import com.asia5b.a5mall.middleware.R
import com.asia5b.a5mall.middleware.utils.DisplayUtils

/**
 * Created by zhangyuncai on 2019/12/21.
 */
abstract class BaseDialog @JvmOverloads constructor(context: Context, themeResId: Int = R.style.BottonDialogTheme) : Dialog(context, themeResId) {

    //屏幕宽度占比
    @FloatRange(from = 0.0, to = 1.0)
    open val widthPercent = 0.0
    open val widthStyle: Int
        get() {
            if (widthPercent > 0) {
                return (DisplayUtils.getScreenWidthAndHight(context)[0] * widthPercent).toInt()
            }
            return WindowManager.LayoutParams.MATCH_PARENT
        }

    //屏幕高度占比
    @FloatRange(from = 0.0, to = 1.0)
    open val heightPercent = 0.0
    open val heightStyle: Int
        get() {
            if (heightPercent > 0) {
                return (DisplayUtils.getScreenWidthAndHight(context)[1] * heightPercent).toInt()
            }
            return WindowManager.LayoutParams.WRAP_CONTENT
        }

    open val gravity: Int = Gravity.BOTTOM
    open val animations: Int = R.style.DataSheetAnimation

    //确定
    protected var mSureClick: ((Any) -> Unit?)? = null

    //取消
    var mCancelClick: (() -> Unit?)? = null

    //关闭界面
    var mDissmissClick: (() -> Unit?)? = null

    /**
     * 强转数据
     */
    fun <T> setSureClick(callback: (T) -> Unit) {
        mSureClick = {
            callback.invoke(it as T)
        }
    }

   open fun getDataBinding(): View? {
        return null
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setWindowsStyle()
        if (getDataBinding() != null) {
            setContentView(getDataBinding()!!)
        } else {
            setContentView(layoutId)
        }
        initView()
        initEvent()
        setOnDismissListener { mDissmissClick?.invoke() }
    }


    abstract val layoutId: Int
    protected abstract fun initView()
    protected abstract fun initEvent()
    protected open fun setWindowsStyle() {
        //去掉dialog的标题
        requestWindowFeature(Window.FEATURE_NO_TITLE)
        /* 设置与屏幕等宽 */
        val window = window!!
        window.decorView.setPadding(0, 0, 0, 0)
        val lp = window.attributes
        lp.width = widthStyle
        lp.height = heightStyle
        lp.gravity = gravity
        window.attributes = lp
        window.setWindowAnimations(animations)
    }

    protected fun getString(@StringRes s: Int): String {
        return context.getString(s)
    }

}